package it.fuesi.synotools.services.tasks.search;

import android.util.Log;

import it.fuesi.synotools.R;
import it.fuesi.synotools.adapters.EmuleSearchAdapter;
import it.fuesi.synotools.constants.ApiErrorCode;
import it.fuesi.synotools.helpers.FormatHelper;
import it.fuesi.synotools.model.base.ErrorObject;
import it.fuesi.synotools.model.emulesearch.EmuleSearchClientParameters;
import it.fuesi.synotools.model.emulesearch.EmuleSearchResultsDataObject;
import it.fuesi.synotools.model.emulesearch.EmuleSearchResultsResponse;
import it.fuesi.synotools.model.emulesearch.EmuleSearchStartResponse;
import it.fuesi.synotools.services.client.EmuleSearchClient;
import it.fuesi.synotools.services.client.ServiceClientFactory;
import it.fuesi.synotools.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class EmuleSearchTask extends BaseTask<EmuleSearchResultsResponse, EmuleSearchResultsDataObject, EmuleSearchClientParameters> {

    private static final String TAG = EmuleSearchTask.class.getName();

    public EmuleSearchTask(EmuleSearchAdapter adapter){
        super(adapter);
    }


    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public EmuleSearchResultsResponse run(EmuleSearchClientParameters params)  throws Exception {
            EmuleSearchClient client = ServiceClientFactory.getClient(EmuleSearchClient.class);

            final int searchId;


            long start = System.currentTimeMillis();

            Log.d(TAG, "Starting search --> ");
            publishProgress(getContext().getString(R.string.progress_start_search));
            EmuleSearchStartResponse startResponse = client.start(params.getKey(),"generalsearch", 1, 0, 0);
            if(startResponse.isSuccess())
                searchId = startResponse.getSearchid();
            else{
                searchId = -1;
                //TODO: manage start error
            }


            boolean finished = false;
            EmuleSearchResultsResponse resp = null;
            while(!finished){
                publishProgress(getContext().getString(R.string.progress_query_search) + FormatHelper.formatTimeMillis(getContext(), System.currentTimeMillis() - start));
                resp = client.list(searchId, "result_enum","SOURCE","DESC",0,100);
                resp.setSearchid(searchId);
                if(!resp.isSuccess()){
                    finished = true;
                   // resp.setSuccess(true);



                }else{
                    EmuleSearchResultsDataObject data = new EmuleSearchResultsDataObject();
                    data.setItems(resp.getItems());
                    resp.setData(data);
                    finished = resp.isSearchdone();
                }
            }


            return resp;

    }


}
